package com.chisheng.caa.util;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.Set;

/**
 * Spring Validation 手动执行校验工具
 */
@Component
public final class ValidationUtil {

    @Resource
    private Validator validator;

    /**
     * 校验实体类。
     */
    public <T> void validate(T t) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
        if (constraintViolations.size() > 0) {
            StringBuilder validateError = new StringBuilder();
            for (ConstraintViolation<T> constraintViolation : constraintViolations) {
                validateError.append(constraintViolation.getMessage()).append(",");
            }

            validateError.deleteCharAt(validateError.length() - 1);
            throw new ValidationException(validateError.toString());
        }
    }

}